import { udp, OType } from '@cscec/udp-ui';
import type { ICustomHooks } from '../interface';
import { getRequestByConfig } from '../service';

export default function ({ busType }: { busType: string }) {
  return {
    namespace: `${busType}-detail-state`,
    state: {
      busType,
      activeTab: {}, // 容器激活的tab页，可能会有多tabs组件的情况
      data: {}, // 表名作为key，表单或列表的数据源作为value，例：{pms3_aq_chk_m:{}, pms3_aq_chk_d:[]}
    },
    reducers: {
      updateData(state: { data: any; }, { payload }: any) {
        console.log('[debug] updateData', payload);
        return { ...state, data: { ...state.data, ...payload } };
      },
    },
    effects: {
      * loadData({ payload }: any, { call, put }: any): any {
        const data = yield call(loadData, payload);
        yield put({ type: 'updateData', payload: data });
      }
    },
  };
}

/**
 * 服务端加载明细数据
 * @param url {form, grid} ui元数据配置的url地址
 * @param initState 根据ui元数据动态生成的初始状态值
 * @param page 页面实例
 * @param impParams imp相关参数
 * @param masterTableName 主表名
 * @param data 其他参数
 */
async function loadData({
  initState, page, impParams, masterTableName, ...data
}: any) {
  let result: any = initState;
  data.id = page.Id;
  const listInfo = page.getLayout();  //返回uiInfo，对应列表就是listInfo,编辑就是editInfo
  const defaultParams = {
    ...data,
    bizCode: page.busType,
  };
  const { transferDetailData, transferDetailReqParams }: ICustomHooks = await page.createHooks();
  if (data.id) {
    const hookParams = await transferDetailReqParams?.(defaultParams);

    const request = getRequestByConfig(page.getMicroServiceName(), listInfo.requestDetail || {
      method: 'get',
      url: '/customForm/customPC/getInfo',
    });
    result = await request({
      data: {
        ...defaultParams,
        ...hookParams,
      },
    });
    
    if (page.oType === OType.Add) {
      // TODO
    }
  }

  if (result?.hasOwnProperty('code') && result.code !== 0) {
    await udp.alert(result.message || '服务器返回错误');
    return initState;
  }
  const hookReturn = await transferDetailData?.(result?.data || result, { data, oType: page.oType });
  result = hookReturn || result;
  if (!data.id) {
    return { ...initState, ...(result?.data || result) };
  }
  result = result.data || result;
  return Object.keys(result).reduce((p, c) => {
    const record = udp.parseJson(result[c]);
    return {
      ...p,
      [c]: record,
    };
  }, initState);
}
